package com.gavindon.android.view.video

import android.content.Intent
import android.graphics.Color
import android.graphics.Paint
import android.os.Bundle
import android.os.Handler
import android.text.Spannable
import android.text.SpannableString
import android.text.Spanned.SPAN_INCLUSIVE_INCLUSIVE
import android.text.style.AbsoluteSizeSpan
import android.text.style.ForegroundColorSpan
import android.view.KeyEvent
import android.view.View
import android.view.ViewGroup
import android.widget.FrameLayout
import android.widget.ImageView
import android.widget.LinearLayout
import android.widget.TextView
import androidx.constraintlayout.widget.ConstraintLayout
import androidx.core.os.bundleOf
import androidx.core.text.HtmlCompat
import androidx.core.text.HtmlCompat.FROM_HTML_MODE_COMPACT
import androidx.core.view.setPadding
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentManager
import androidx.fragment.app.FragmentStatePagerAdapter
import androidx.leanback.tab.LeanbackTabLayout
import androidx.leanback.tab.LeanbackViewPager
import androidx.leanback.widget.HorizontalGridView
import com.gavindon.android.R
import com.gavindon.android.adapters.VideoComboAdapter
import com.gavindon.android.base.*
import com.gavindon.android.entity.ComboResp
import com.gavindon.android.entity.LoginStatus
import com.gavindon.android.entity.VideoTreeResp
import com.gavindon.android.network.DataResult
import com.gavindon.android.network.RetrofitHelp
import com.gavindon.android.utils.*
import com.gavindon.android.view.combo.BuyActivity
import com.gavindon.android.view.combo.ComboLstActivity
import com.gavindon.android.view.start.LoginActivity
import com.gavindon.android.viewmodel.CommonViewModel
import com.gavindon.android.viewmodel.VideoViewModel
import com.gavindon.android.widget.FocusViewUtils
import com.gavindon.android.widget.VodVideoPlayer
import com.gavindon.android.widget.video.PlayCompletionListener
import com.google.android.material.tabs.TabLayout
import com.orhanobut.logger.Logger
import com.shuyu.gsyvideoplayer.GSYVideoManager
import com.shuyu.gsyvideoplayer.utils.GSYVideoType
import kotlinx.coroutines.runBlocking
import org.greenrobot.eventbus.EventBus
import org.jetbrains.anko.*


/**
 * description: 视频播放带详情
 * Created by liNan on  2022-2-9 21:57
 */
class VideoDetailActivity : BaseActivity(), VideoDetailCourseFragment.CallBackPlay {
    override val layoutId = R.layout.activity_video_detail
    private lateinit var mViewModel: VideoViewModel
    private lateinit var mCommonViewModel: CommonViewModel

    lateinit var btnFullScreen: LinearLayout
    private lateinit var btnCollect: LinearLayout
    private lateinit var tvCollect: TextView
    private lateinit var btnVip: LinearLayout
    private lateinit var btnBuy: LinearLayout
    private lateinit var tvBuy: TextView
    private lateinit var tvNowPrice: TextView
    private lateinit var tvOrignPrice: TextView
    private lateinit var videoTitle: TextView
    private lateinit var videoIntroduce: TextView
    private lateinit var rootDetailView: ConstraintLayout
    private lateinit var cslRight: ConstraintLayout
    private lateinit var tvExpiredTime: TextView
    private lateinit var ivIntroMore: ImageView

    //推荐套餐rv
    lateinit var recommendComboRv: HorizontalGridView
    private var isFull = false

    //课时
    private lateinit var videoClass: TextView
    private val videoPlayer: VodVideoPlayer by lazy {
        findViewById(R.id.video_left_half)
    }
    private val fmlLesson: FrameLayout by lazy {
        findViewById(R.id.fml_lesson)
    }
    val mViewPager: LeanbackViewPager by lazy {
        findViewById(R.id.lean_vp)
    }
    val mTabLayout: LeanbackTabLayout by lazy {
        findViewById(R.id.lean_tablayout)
    }
    private var courseId: String? = ""
    private var courseName: String? = ""
    private var lessonId: String = ""

    //课程是否免费 1免费
    private var courseIsFree = "-1"

    //是否有课时分组 tabLayout
    var hasTabLayout = false
    var tabPosition = 0
    private var videoDetailPagerAdapter: VideoDetailPagerAdapter? = null
    private var videoWidth = 0
    private var videoHeight = 0

    private var videoPlayPosition = 0
    private var videoPlayPercent = 0
    override fun onInit(savedInstanceState: Bundle?) {
        btnFullScreen = findViewById(R.id.ll_full_screen)
        btnCollect = findViewById(R.id.ll_collect)
        tvCollect = findViewById(R.id.tv_collect)
        btnVip = findViewById(R.id.ll_vip)
        btnBuy = findViewById(R.id.ll_buy)
        tvBuy = findViewById(R.id.tv_buy)
        tvExpiredTime = findViewById(R.id.tv_expired_time)
        tvOrignPrice = findViewById(R.id.tv_orign_price)
        tvNowPrice = findViewById(R.id.tv_now_price)
        videoTitle = findViewById(R.id.tv_video_title)
        videoIntroduce = findViewById(R.id.tv_video_intro)
        videoClass = findViewById(R.id.tv_video_class)
        rootDetailView = findViewById(R.id.root_detail)
        recommendComboRv = findViewById(R.id.recommend_combo)
        cslRight = findViewById(R.id.cs_right)
        ivIntroMore = findViewById(R.id.intro_more)
        FocusViewUtils.scaleView(btnFullScreen, 0)
        FocusViewUtils.scaleView(btnCollect, 0)
        FocusViewUtils.scaleView(btnVip, 0)
        btnFullScreen.postDelayed({ btnFullScreen.requestFocus() }, 200)
        courseId = intent.getStringExtra(INTENT_COURSE_ID)
        courseName = intent.getStringExtra(INTENT_COURSE_NAME)
        videoDetailPagerAdapter = VideoDetailPagerAdapter(supportFragmentManager, null)
        btnFullScreen.setOnClickListener {
            videoPlayer.isShowFullAnimation = false
            videoPlayer.isRotateViewAuto = false
            videoPlayer.isNeedOrientationUtils = false
            val videoLayoutParams = ViewGroup.LayoutParams(matchParent, matchParent)
            videoPlayer.layoutParams = videoLayoutParams
            videoWidth = videoPlayer.width
            videoHeight = videoPlayer.height
            rootDetailView.setPadding(0)
            isFull = true
//            videoPlayer.startWindowFullscreen(this, false, false)
            toggleFullFocus(true)
        }
        GSYVideoType.enableMediaCodec()
        GSYVideoType.enableMediaCodecTexture()
        init()
        initRecommendComb()
        //防止viewpager预加载，导致播放第二个tab
        mTabLayout.addOnTabSelectedListener(object : TabLayout.OnTabSelectedListener {
            override fun onTabSelected(tab: TabLayout.Tab?) {
                tabPosition = tab?.position ?: 0
            }

            override fun onTabUnselected(tab: TabLayout.Tab?) {
            }

            override fun onTabReselected(tab: TabLayout.Tab?) {
            }


        })
    }

    /**
     * 视频全屏时 按键会继续切换焦点
     */
    private fun toggleFullFocus(isFull: Boolean) {
        btnFullScreen.isFocusable = !isFull
        btnCollect.isFocusable = !isFull
        btnVip.isFocusable = !isFull
        mTabLayout.isFocusable = !isFull
        mViewPager.isFocusable = !isFull
        videoPlayer.isFocusable = isFull
        ivIntroMore.isFocusable = !isFull
        if (isFull) {
            videoPlayer.requestFocus()
        } else {
            btnFullScreen.requestFocus()
        }
    }

    override fun onBackPressed() {
//        if (GSYVideoManager.backFromWindowFull(this)) {
//            toggleFullFocus(false)
//            return
//        }
        //退出全屏
        if (isFull) {
            /*       val layoutparams = ViewGroup.LayoutParams(videoWidth, videoHeight)
                   rootDetailView.setPadding(dip(50), dip(30), dip(50), dip(30))
                   videoPlayer.layoutParams = layoutparams*/
            val layoutParams = ConstraintLayout.LayoutParams(videoWidth, videoHeight)
            layoutParams.leftToLeft = R.id.guide_start
            layoutParams.rightToLeft = R.id.cs_right
            layoutParams.topToTop = R.id.guide_top
            videoPlayer.layoutParams = layoutParams
            isFull = !isFull
            toggleFullFocus(false)
            return
        }
        //保存视频进度 ms->s
        if (lessonId.isNotEmpty() && videoPlayPosition > 1000) {
//            mCommonViewModel.pushVideoProgress(lessonId, videoPlayPosition / 1000)
            Logger.i("返回播放位置$videoPlayPosition===")
            try {
                runBlocking {
                    RetrofitHelp.create().clientLessonProgress(lessonId, videoPlayPosition / 1000)
                }
            } catch (err: Exception) {
            }
        }
        super.onBackPressed()
    }


    override fun onPause() {
        super.onPause()
        videoPlayer.onVideoPause()
    }

    override fun onResume() {
        super.onResume()
        videoPlayer.onVideoResume()
//        if (LoginStatus.hasLogin) {
//            collectAction()
//        }
    }

    override fun onDestroy() {
        GSYVideoManager.releaseAllVideos()
        //清除全局保存的数据
        if (SaveCurrentView.currentView != null) {
            SaveCurrentView.currentView = null
        }
        SaveAdapters.totalData.clear()
        super.onDestroy()

    }

    private fun init() {
        mViewModel = getViewModel()
        mCommonViewModel = getViewModel()
        //收藏状态
        collectAction()
        btnCollect.click {
            if (tvCollect.text == "收藏") {
                addCollect()
            } else {
                cancelCollect()
            }
        }
        checkCoursePayStatus(this.courseId!!, GoodsType.LESSON.ordinal.toString())
        //跳转购买页面购买套餐
        btnBuy.click {
            if (tvBuy.text == "购买") {
                startActivity<BuyActivity>(
                    Pair(INTENT_COMBO_ID, courseId),
                    Pair(INTENT_GOODS_TYPE, GoodsType.LESSON.ordinal)
                )
            } else {
                toast("该课程已购买")
            }

//            startActivity<ComboLstActivity>(Pair(INTENT_COURSE_ID, courseId))
        }
        /*获取课程信息*/
        mViewModel.getCourseDetail(courseId!!).observe(this) {
            if (it is DataResult.Success) {
                //课程是否免费
                courseIsFree = it.data.isFree
                videoTitle.text = it.data.courseName
                val introduce =
                    HtmlCompat.fromHtml(it.data.courseIntroduction, FROM_HTML_MODE_COMPACT)
                val html = "介绍:${introduce}"
                val spannable = SpannableString(html)
                val absoluteSizeSpan = AbsoluteSizeSpan(sp(18))
                val textColorSpan = ForegroundColorSpan(Color.parseColor("#b3ffffff"))
                val textColorSpan2 = ForegroundColorSpan(Color.parseColor("#80ffffff"))
                val absoluteSizeSpan2 = AbsoluteSizeSpan(sp(16))
                spannable.setSpan(absoluteSizeSpan, 0, 3, Spannable.SPAN_INCLUSIVE_EXCLUSIVE)
                spannable.setSpan(textColorSpan, 0, 3, Spannable.SPAN_INCLUSIVE_EXCLUSIVE)
                spannable.setSpan(absoluteSizeSpan2, 3, html.length, SPAN_INCLUSIVE_INCLUSIVE)
                spannable.setSpan(textColorSpan2, 3, html.length, SPAN_INCLUSIVE_INCLUSIVE)
                videoIntroduce.text = spannable
                videoClass.text = "${it.data.numTotalLesson}节课 ｜ ${it.data.videoTotalDuration}分钟"
                ivIntroMore.setOnClickListener {
                    val dialog = IntroMoreDialog(introduce.toString())
                    dialog.show(supportFragmentManager, "introduce")
                }
                if (courseIsFree.toInt() == CourseFreeStatus.FREE.ordinal) {
                    btnBuy.visibility = View.GONE

                } else {
                    btnBuy.visibility = View.VISIBLE
                    tvOrignPrice.text =
                        if (!it.data.originalPrice.isNullOrEmpty()) "￥${it.data.originalPrice}" else ""
                    tvOrignPrice.paint.flags = Paint.STRIKE_THRU_TEXT_FLAG
                    tvNowPrice.text =
                        if (!it.data.presentPrice.isNullOrEmpty()) "￥${it.data.presentPrice}" else ""
                    tvExpiredTime.text =
                        if (it.data.serviceLife != null && it.data.serviceLife == "0")
                            "权益有效期:永久有效" else "权益有效期:${it.data.serviceLife}${it.data.serviceLifeCompany?.ymd()}"
                }
                getCourseInfo()
            }
        }
        //监听进度回调
        videoPlayer.setGSYVideoProgressListener { progress, secProgress, currentPosition, duration ->
            videoPlayPosition = currentPosition
            videoPlayPercent = progress
            Logger.i("前播放位置$currentPosition===$duration")
        }
        //监听播放完成回调
        videoPlayer.setPlayFinishListener(object : PlayCompletionListener {
            override fun onPlayFinish() {
                //当播放完成时viewpager获取焦点使之能够自动切换下一集
                mViewPager.isFocusable = true
                EventBus.getDefault().post(RecordPlay(playPosition, tabPosition))
            }

            override fun onPlayStart() {
                //当开始播放时如果是全屏则使章节viewpager失去焦点
                mViewPager.isFocusable = !isFull
            }
        })

    }


    /**
     * 获取课程章节目录
     */
    private fun getCourseInfo() {
        /*获取课程目录信息 再根据lessonId获取对应的章节*/
        mViewModel.getCourseTree(courseId!!).observe(this, {
            if (it is DataResult.Success) {
                val tabLst = mutableListOf<VideoTreeResp>()
                val lessons = mutableListOf<VideoTreeResp>()
                for (item in it.data) {
                    //设置课程是否免费
                    item.isFree = courseIsFree
                    if (item.catalogType == "chapter") {
                        //tab 数据
                        item.isFree = courseIsFree
                        tabLst.add(item)
                    } else {
                        item.isFree = courseIsFree
                        lessons.add(item)
                        val lessonId = item.linkObjId
//                        fetchVideoItemData(lessonId, item.courseId, item.freeViewing)
                        this.lessonId = lessonId
                    }
                }
                //如果有章节才会有TabLayout ->tabLst
                initTab(tabLst, lessons)
            }
        })
    }

    /**
     * 收藏
     */
    private fun collectAction() {
        mCommonViewModel.clientCollectStatus(courseId!!).observe(this) {
            if (it is DataResult.Success) {
                if (it.data) {
                    tvCollect.text = "已收藏"
                } else {
                    tvCollect.text = "收藏"
                }
            }
        }
    }


    private fun addCollect() {
        mCommonViewModel.clientCollectAdd(courseId!!).observe(this) {
            if (it is DataResult.Success) {
                tvCollect.text = "已收藏"
            }
        }
    }

    private fun cancelCollect() {
        mCommonViewModel.clientCollectCancel(courseId!!).observe(this) {
            if (it is DataResult.Success) {
                tvCollect.text = "收藏"
            }
        }
    }

    private fun initTab(topTabs: MutableList<VideoTreeResp>, lessons: MutableList<VideoTreeResp>) {
        if (!topTabs.isNullOrEmpty()) {
            hasTabLayout = true
            mTabLayout.isFocusable = true
            mTabLayout.requestFocus()
            val tabLst = topTabs.map { it.catalogName }
            //把没有分章节的课程添加到第一章下面
            topTabs[0].children.addAll(lessons)
            videoDetailPagerAdapter?.setNewTab(topTabs)
            mViewPager.adapter = videoDetailPagerAdapter
            mTabLayout.setupWithViewPager(mViewPager)
            var cursoId = ""
            var videoView = "-1"
            //xxxxxxxxxxxxxxxxxxxxxxx
            when {
                topTabs[0].children.isNullOrEmpty() -> {
                    lessonId = topTabs[0].linkObjId
                    cursoId = topTabs[0].courseId
                    videoView = topTabs[0].freeViewing
                }
                topTabs[0].children[0].children.isNullOrEmpty() -> {
                    lessonId = topTabs[0].children[0].linkObjId
                    cursoId = topTabs[0].children[0].courseId
                    videoView = topTabs[0].children[0].freeViewing
                }
                topTabs[0].children[0].children[0].children.isNullOrEmpty() -> {
                    lessonId = topTabs[0].children[0].children[0].linkObjId
                    cursoId = topTabs[0].children[0].children[0].courseId
                    videoView = topTabs[0].children[0].children[0].freeViewing
                }
            }
            fetchVideoItemData(lessonId, videoView)
            tabLst.forEachIndexed { index, s ->
                val tab = mTabLayout.getTabAt(index)
                tab?.let {
                    val customView = layoutInflater.inflate(R.layout.custom_video_tab, null, false)
                    val customTv = customView.findViewById<TextView>(R.id.tv_video_tab)
                    customTv.text = s
                    tab.customView = customView
                }
            }
        } else {
            hasTabLayout = false
            initGridView(lessons)
            if (lessons.size > 0) {
                lessonId = lessons[0].linkObjId
                fetchVideoItemData(lessonId, lessons[0].freeViewing)
            }
        }
    }

    /**
     * 不使用viewPager时，直接使用Fragment承载数据
     */
    private fun initGridView(videoTreeResp: MutableList<VideoTreeResp>) {
        if (!videoTreeResp.isNullOrEmpty()) {
            mViewPager.visibility = View.GONE
            mTabLayout.visibility = View.GONE
            //fragment接收的是个VideoTreeResp对象所以把所有的课程都加到children中传过去一个对象而不是一个List
            videoTreeResp[0].children.addAll(videoTreeResp)
            val fragment = VideoDetailCourseFragment()
            fragment.arguments = bundleOf(Pair(INTENT_FRAGMENT_VIDEO, videoTreeResp[0]))
            val transaction = supportFragmentManager.beginTransaction()
            transaction.replace(R.id.fml_lesson, fragment)
            transaction.commitAllowingStateLoss()
            btnFullScreen.setOnKeyListener { v, keyCode, event ->
                if (event.action == KeyEvent.ACTION_DOWN) {
                    if (keyCode == KeyEvent.KEYCODE_DPAD_DOWN) {
                        mViewPager.visibility = View.GONE
                        mTabLayout.visibility = View.GONE
                        return@setOnKeyListener false
                    }
                }
                return@setOnKeyListener false

            }
        }
    }

    //章节课程点击时，判断是否免费跳转购买页面
    var isItemClick = false
    private var free = "-1"
    private var playPosition = 0

    //当前章节观看到哪个时间节点
    private var watchSeconds = 0

    /**
     * 提供给Fragment可调用 更新打开当前课程
     */
    override fun fetchVideoItemData(
        currentLessonId: String,
        freeViewing: String,
        playPosition: Int
    ) {
        //在打开下一节课程时 保存当前观看进度
        if (lessonId.isNotEmpty() && videoPlayPosition > 1000) {
            mCommonViewModel.pushVideoProgress(lessonId, videoPlayPosition / 1000)
            videoPlayPosition = 0
            videoPlayPercent = 0
        }
        //需要放到全局，否则freeViewing值会变成其他；
        free = freeViewing
        this.playPosition = playPosition
        lessonId = currentLessonId
        mCommonViewModel.getStudyRecord(currentLessonId).observe(this) {
            //获取当前观看进度
            if (it is DataResult.Success) {
                //1代表视频已看完
                if (it.data?.complete == 1) {
                    watchSeconds = 0
                } else {
                    watchSeconds = it.data?.watchedSecond ?: 0
                }
            }
            videoPlayer.release()
            mViewModel.getLessonDetail(lessonId).observe(this, { detail ->
                if (detail is DataResult.Success) {
                    //如果整个课程免费的话，不需要判断章节是否免费
                    if (courseIsFree == CourseFreeStatus.FREE.ordinal.toString()) {
                        videoPlayer.setUp(
                            detail.data.fileUrl,
                            false,
                            detail.data.catalogName
                        )
                        videoPlayer.postDelayed(
                            {
                                videoPlayer.seekTo(watchSeconds * 1000L)
                            }, 800
                        )
                        videoPlayer.startPlayLogic()
                        //更新播放动画显示
                        EventBus.getDefault()
                            .post(PlayLottie(this.playPosition, tabPosition))
                    } else {
                        //如果章节课程状态是可以免费观看
                        if (free == FreeStatus.FREE.ordinal.toString()) {
                            videoPlayer.setUp(detail.data.fileUrl, false, detail.data.catalogName)
                            videoPlayer.postDelayed(
                                { videoPlayer.seekTo(watchSeconds * 1000L) }, 800
                            )
                            videoPlayer.startPlayLogic()
                            EventBus.getDefault()
                                .post(PlayLottie(this.playPosition, tabPosition))
                        } else {

                            if (!LoginStatus.hasLogin) {
                                toast("请先登录")
                                this.startActivityForResult<LoginActivity>(requestLoginCode)
                            } else {
                                //检测是否支付，如果已经支付可以观看
                                checkPayResult(this.courseId!!, GoodsType.LESSON.ordinal.toString())
                                setCheckListener {
                                    if (it) {
                                        videoPlayer.setUp(
                                            detail.data.fileUrl,
                                            false,
                                            detail.data.catalogName
                                        )
                                        videoPlayer.postDelayed(
                                            { videoPlayer.seekTo(watchSeconds * 1000L) }, 800
                                        )
                                        videoPlayer.startPlayLogic()
                                        EventBus.getDefault()
                                            .post(PlayLottie(this.playPosition, tabPosition))
                                    } else {
                                        if (isItemClick) {
                                            startActivityForResult<BuyActivity>(
                                                BUY_REQUEST_CODE,
                                                Pair(
                                                    INTENT_GOODS_TYPE,
                                                    GoodsType.LESSON.ordinal
                                                ),
                                                Pair(
                                                    INTENT_COMBO_ID,
                                                    courseId
                                                ),
                                                Pair(
                                                    INTENT_PLAY_POSITION,
                                                    this.playPosition
                                                ),
                                            )
                                        }
                                    }
                                }
                            }


                        }
                    }
                }
            })

        }
    }

    /**
     * 推荐套餐
     */
    val comboAdapter = VideoComboAdapter(R.layout.adapter_video_combo, null)
    private fun initRecommendComb() {
        recommendComboRv.adapter = comboAdapter
        recommendComboRv.setItemSpacing(dip(20))
        recommendComboRv.setNumRows(1)
        mCommonViewModel.queryCombLst(courseId ?: "").observe(this) {
            if (it is DataResult.Success) {
                //如果有推荐套餐，显示列表
                recommendComboRv.visibility = View.VISIBLE
                comboAdapter.setList(it.data)
            } else {
                recommendComboRv.visibility = View.GONE
            }
        }
        comboAdapter.setOnItemClickListener { adapter, view, position ->
            val data = adapter.getItem(position) as ComboResp
            if (LoginStatus.hasLogin) {
                startActivity<ComboLstActivity>(
                    Pair(INTENT_PACKAGE_ID, data.packageId),
                    Pair(INTENT_COURSE_ID, courseId)
                )
            } else {
                toast("请先登录")
                this.startActivityForResult<LoginActivity>(requestLoginCode)
            }
        }
    }

    private fun checkPayResult(id: String, orderType: String) {
        mCommonViewModel.checkIsCanLook(orderType, id).observe(this) {
            if (it is DataResult.Success) {
                if (!it.data.isNullOrEmpty()) {
                    when (it.data[0].validity) {
                        0 -> canLookListener?.invoke(false)
                        1 -> {
                            canLookListener?.invoke(false)
                        }
                        2 -> {
                            canLookListener?.invoke(true)
                        }
                    }
                } else {
                    canLookListener?.invoke(false)
                }
            } else {
                canLookListener?.invoke(false)
            }
        }
    }

    //支付成功之后，显示已购买
    fun showHasBuy() {
        tvBuy.text = "已购买"
    }

    private fun checkCoursePayStatus(id: String, orderType: String) {
        mCommonViewModel.checkIsCanLook(orderType, id).observe(this) {
            if (it is DataResult.Success) {
                if (!it.data.isNullOrEmpty()) {
                    when (it.data[0].validity) {
                        2 -> {
                            tvBuy.text = "已购买"
                        }
                        else -> {
                            tvBuy.text = "购买"
                        }
                    }
                } else {
                    tvBuy.text = "购买"
                }
            } else {
                tvBuy.text = "购买"
            }
        }
    }

    private var canLookListener: ((Boolean) -> Unit)? = null
    private fun setCheckListener(listener: (Boolean) -> Unit) {
        this.canLookListener = listener
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        if (requestCode == BUY_REQUEST_CODE) {
            val playPosition = data?.getIntExtra("playPosition", 0)
            if (playPosition != null) {
                Handler().postDelayed({
                    EventBus.getDefault().post(PayResultPlay(playPosition))
                }, 500)
            }
        }
        //如果登录成功
        if (requestCode == requestLoginCode) {
            if (LoginStatus.hasLogin) {
                collectAction()
                initRecommendComb()
                checkCoursePayStatus(this.courseId!!, GoodsType.LESSON.ordinal.toString())
            }
        }
        super.onActivityResult(requestCode, resultCode, data)
    }

}

class VideoDetailPagerAdapter(fm: FragmentManager, dataLst: List<VideoTreeResp>?) :
    FragmentStatePagerAdapter(fm, BEHAVIOR_RESUME_ONLY_CURRENT_FRAGMENT) {


    private var tabData: List<VideoTreeResp>? = dataLst


    override fun getCount() = tabData?.size ?: 0


    fun setNewTab(tabs: List<VideoTreeResp>?) {
        this.tabData = tabs
        notifyDataSetChanged()
    }


    override fun getItem(position: Int): Fragment {
        val fragment = VideoDetailCourseFragment()
        fragment.arguments = bundleOf(
            Pair(INTENT_FRAGMENT_VIDEO, tabData?.get(position)),
            Pair("index", position)
        )
        return fragment
    }

    override fun getPageTitle(position: Int): CharSequence? {
        val tabLst = tabData?.map { it.catalogName }
        return tabLst?.get(position)
    }
}

